package com.wk.springboot.config;

import com.wk.springboot.bean.Person;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;

/**
 * @Classname ItemReaderConfig
 * @Description 这个类是要定义ItemReader的
 * @Date 2020/4/7 9:52
 * @Author by weikai
 */
@Configuration
public class ItemReaderConfig {


  /**
   * reader读取资源的途径有以下几种
   * 1.系统文件：通常是一个文件，里面定义了数据的属性，每个属性会以指定的分隔符分割（如","）
   * 2.xml
   * 3.数据库
   */

  /**
   * 读取一个系统文件
   */
//  @Bean
  public FlatFileItemReader flatFileItemReader() {
    FlatFileItemReaderBuilder<Person> reader = new FlatFileItemReaderBuilder<Person>()
        .name("csvFlatFileItemReader")
        .resource(new FileSystemResource("file://outputs/file.txt"));
    return reader.build();
  }

  /**
   * 通过读取配置文件中的值，在运行期获取资源
   */
  @Bean
  public FlatFileItemReaderBuilder<Person> flatFileItemReaderBuilder(
      @Value("${input.file.name}") String name) {
    return new FlatFileItemReaderBuilder<Person>()
        .name("csvFlatFileItemReader")
        .resource(new FileSystemResource(name));
  }

  /**
   * 1.stepScope的作用在于在step被执行时，这个bean才会被初始化。
   * 因为这些资源不是spring 容器中的，这样避免了资源找不到问题
   * 2.通过通配符"#{}"指定资源
   */


  /**
   * 通过jobParameter传值
   */
  @StepScope
  @Bean
  public FlatFileItemReaderBuilder<Person> flatFileItemReaderJobParameter(
      @Value("#{jobParameters['input.file.name']}") String name) {
    return new FlatFileItemReaderBuilder<Person>()
        .name("csvFlatFileItemReader")
        .resource(new FileSystemResource(name));
  }

  /**
   * 通过jobExecutionContext传参
   */
  @StepScope
  @Bean
  public FlatFileItemReaderBuilder<Person> flatFileItemReaderJobExecutionContext(
      @Value("#{jobExecutionContext['input.file.name']}") String name) {
    return new FlatFileItemReaderBuilder<Person>()
        .name("csvFlatFileItemReader")
        .resource(new FileSystemResource(name));
  }

  /**
   * 通过stepExecutionContext传参
   */
  @StepScope
  @Bean
  public FlatFileItemReaderBuilder<Person> flatFileItemReaderStepExecutionContext(
      @Value("#{stepExecutionContext['input.file.name']}") String name) {
    return new FlatFileItemReaderBuilder<Person>()
        .name("csvFlatFileItemReader")
        .resource(new FileSystemResource(name));
  }

  /**
   * 当然也有jobScope
   */
  @JobScope
  @Bean
  public FlatFileItemReader flatFileItemReader(
      @Value("#{jobExecutionContext['input.name']}") String name) {
    return new FlatFileItemReaderBuilder<Person>()
        .name("csvFlatFileItemReader")
        .resource(new FileSystemResource(name)).build();
  }


}
